package org.test.client.listener;

import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JComponent;

/**
 * 为 某一个 组件 上的 某些矩形 区域增加鼠标监听
 * @author Guodeqi
 *
 */
public class CommonMouseListenerForRect extends MouseAdapter{
	private JComponent comp;
	private  Container parent = null;
	
	protected List<Rectangle> focusList = null;
	protected List<ClickAction> actions;
	protected List<EnteredAction> enteredActions;
	
	public CommonMouseListenerForRect(JComponent comp){
		this.comp = comp;
		parent = comp.getParent();
		
		focusList = new LinkedList<Rectangle>();
		actions = new LinkedList<ClickAction>();
		enteredActions = new LinkedList<EnteredAction>();
	}
	
	@Override
	public void mouseEntered(MouseEvent me) {
		int index = getRectIndexByPoint(me.getPoint());
		if(index != -1){
			enteredActions.get(index).doOnEntered(me);
		}
	}

	@Override
	public void mouseExited(MouseEvent me) {
		int index = getRectIndexByPoint(me.getPoint());
		if(index != -1){
			enteredActions.get(index).doOnExited(me);
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent me) {
		int index = getRectIndexByPoint(me.getPoint());
		if(index != -1){
			actions.get(index).doOnClick(me);
		}
	}
	
	public int getRectIndexByPoint(Point p){
		int size = focusList.size();
		if(size > 0){
			for(int i=0;i<size;i++){
				Rectangle rect = focusList.get(i);
				if(rect.contains(p)){
					return i;
				}
			}
		}
		return -1;
	}
	
	public void addListenerForRect(Rectangle rect,ClickAction ca,EnteredAction ea){
		focusList.add(rect);
		actions.add(ca);
		enteredActions.add(ea);
	}
}
